for (i in 1:4) {
    x <- i + 1
    print(x)
}


i <- 1
while (i < 5) {
    # i <- i + 1
    print(i)
}


i <- 1
repeat {
    i <- i + 1

    if (i == 5) {
        next
    }
    print(i)

    if (i == 8) {
        break
    }
}

library(foreach)
foreach(i = 1:6) %do% {
    i + 1
}


lapply(1:4, \(i) {
    i + 1
})
sapply(1:4, function(i) {
    i + 1
})




suppressMessages(library(tidyverse))
map(1:4, function(x) x + 1)
map_vec(1:4, function(x) x + 1)


map2(1:4, 4:1, function(x, y) x + y)
pmap(list(1:4, 1:4, 1:4,1:4),function(x, y, z,i) x + y + z + i)


map(1:4, ~ .x +1)

map(1:4, \(x) x + 1)


p = c(.01,.0001,5e-8)
a = letters[1:12]


d = expand.grid(p,a)
map2(d[,1],d[,2] ,~ paste0(.x,'___',.y))

furrr::future_map2()

map(p, \(.x) {
    map(a, \(.y) paste0(.x,'___',.y))
})

{
    a <- Sys.time()
    lapply(1:4, function(x) {
        Sys.sleep(.5)
    })
    b <- Sys.time()
    b - a
}

{
    library(foreach)
    library("doParallel")
    cl <- makeCluster(4)
    registerDoParallel(cl)
    a <- Sys.time()
    foreach(i = 1:4) %dopar% Sys.sleep(.5)
    b <- Sys.time()
    print(b - a)
    stopCluster(cl)
}

{
    a <- Sys.time()
    tmp <- parallel::mclapply(1:4, FUN = function(x) {
        Sys.sleep(.5)
    }, mc.cores = 2L)
    b <- Sys.time()
    b - a
}

{
    library("doParallel")
    cl <- makeCluster(4)
    registerDoParallel(cl)
    a <- Sys.time()
    parLapply(cl = cl, 1:4, fun = function(x) Sys.sleep(.5))
    b <- Sys.time()
    print(b - a)
    stopCluster(cl)
}

{
    library(furrr)
    plan('multicore', workers = 4)
    a <- Sys.time()
    furrr::future_walk(1:4, .f = function(x) Sys.sleep(.5))
    b <- Sys.time()
    print(b - a)
}

